package com.wheel.autoconfigure.web.mvc.returnvaluehandler;/*
 * <h3>Title:fis-api系统</h3>
 * <p>Copyright (c) 2020, wangnaifei@163.com. All rights reserved.</p>
 * @author wangnaifei@163.com
 */

import com.wheel.core.result.Result;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.reflect.Method;

/**
 * <dt>Description:ResultModelAttributeMethodProcessor</dt>
 * <dd>spring mvc modelandview 返回时处理result</dd>
 * <dd>
 * mvc增加配置
 * public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
 * //拆包Response的result
 * handlers.add(new ResultModelAttributeMethodProcessor());
 * }
 * 查看RequestMappingHandlerAdapter.getDefaultReturnValueHandlers()
 * </dd>
 *
 * @author wangnaifei@163.com
 * @version 1.0 <i>2020/11/24 15:25</i>
 * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
 * @since jdk1.7+
 */
public class ResultModelAttributeMethodProcessor implements HandlerMethodReturnValueHandler {

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        Method method = returnType.getMethod();
        Assert.state(method != null, "No handler method");
        Class<?> containingClass = returnType.getContainingClass();
        Class<?> resolvedType = GenericTypeResolver.resolveReturnType(method, containingClass);
        return resolvedType.isAssignableFrom(Result.class);
    }

    @Override
    public void handleReturnValue(@Nullable Object returnValue, @NonNull MethodParameter returnType, @NonNull ModelAndViewContainer mavContainer, @NonNull NativeWebRequest webRequest) {
        ResultMethodProcessor.formatResult(returnValue, webRequest);
        mavContainer.addAllAttributes(((Result)returnValue).toModel());
    }
}
